#!/usr/bin/env python3
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT


# This script generate list of files that are not referenced from any test (list in JSON format)
# Script only looks at not referenced files from three directories: include, library and profiler
# CK needs to be built with ability to use dependency parser and generate dependencies

# Usage: python3 generate_list_of_files_not_referenced_in_tests -f /path/to/enhanced_dependency_mapping/json/file

import argparse
import subprocess
import json


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-f",
        required=True,
        help="Path to enhanced_dependency_mapping.json file generated by dependency parser",
    )
    args = parser.parse_args()
    return args


def main():
    args = parse_args()

    with open(args.f, "r") as file:
        ref_files = json.load(file)
    file_to_executables = ref_files["file_to_executables"]

    all_files = (
        subprocess.check_output(
            'find ../../include/ ../../library/ ../../profiler/ -type f -iname "*.cpp" -o -iname "*.hpp"',
            shell=True,
        )
        .decode("utf-8")
        .split("\n")
    )
    all_files = all_files[:-1]
    all_files[:] = [x[6:] for x in all_files]

    all_referenced_files = []
    for v in file_to_executables:
        if (
            "composablekernel/include/" in v
            or "composablekernel/library/" in v
            or "composablekernel/profiler/" in v
        ):
            exe_list = file_to_executables[v]
        else:
            continue

        found = any("bin/test_" in el for el in exe_list)
        if found:
            all_referenced_files.append(v)

    not_referenced_files = {"include": [], "library": [], "profiler": []}
    for f in all_files:
        found = any(f in el for el in all_referenced_files)
        if not found:
            pos = f.find("/")
            not_referenced_files[f[:pos]].append(f)

    print(json.dumps(not_referenced_files, indent="\t"))


if __name__ == "__main__":
    main()
